Public Class frmImportGIS

    Private _GISProjectPath As String
    Private _WRDBImport As WRDB.Import.clsWRDBImport
    Private Enum enumUsgs
        Measure
        Daily
        WQ
    End Enum
    Private Enum enumStoret
        Legacy
        Modern
    End Enum
    Private Enum enumMet
        Observed
        Computed
    End Enum

    Private Sub OK_Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOK.Click
        Try
            Visible = False
            Dim NumRecords As Integer = ActiveBrowser.GetRecordCount
            If chkMetObs.Checked AndAlso Not ImportMet(enumMet.Observed) Then Exit Sub
            If chkMetComp.Checked AndAlso Not ImportMet(enumMet.Computed) Then Exit Sub
            If chkUSGSDaily.Checked AndAlso Not ImportUsgs(enumUsgs.Daily) Then Exit Sub
            If chkUSGSFlow.Checked AndAlso Not ImportUsgs(enumUsgs.Measure) Then Exit Sub
            If chkUSGSWQ.Checked AndAlso Not ImportUsgs(enumUsgs.WQ) Then Exit Sub
            If chkSTORETLegacy.Checked AndAlso Not ImportStoret() Then Exit Sub
            If chkSTORETModern.Checked AndAlso Not ImportStoretModern() Then Exit Sub

            'If MainWRDB.PromptImport Then
            '    With New frmTracking(frmTracking.enumTrackingMode.Import, ActiveBrowser.TableName, _GISProjectPath)
            '        If .ShowDialog(Me) = DialogResult.OK Then
            '            clsApplicationSettings.ResetEditTime()
            '        End If
            '        .Dispose()
            '    End With
            'End If
            If MainWRDB.PromptJournal >= clsWRDB.enumJournalPrompt.Import Then frmJournal.GetJournalDescription()
            frmJournal.AddJournalEntry(ActiveTableName, frmJournal.enumJournalEntry.Import, ActiveBrowser.GetRecordCount - NumRecords, , "BASINS")
            clsApplicationSettings.ResetEditTime()

            Me.DialogResult = System.Windows.Forms.DialogResult.OK
        Catch ex As Exception
            ErrorMsg(, ex)
        Finally
            DialogResult = System.Windows.Forms.DialogResult.OK
            Close()
        End Try
    End Sub

    Private Sub Cancel_Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancel.Click
        DialogResult = System.Windows.Forms.DialogResult.Cancel
        Close()
    End Sub

    ''' <summary>
    ''' Look for files that match wildcards
    ''' </summary>
    ''' <param name="wildcard">Wildcard specification</param>
    ''' <returns>Selected file name (without path and extension); if nothing, user cancelled, if empty then none found</returns>
    Private Function GetFile(ByVal path As String, ByVal wildcard As String) As String
        Try
            If Not My.Computer.FileSystem.DirectoryExists(path) Then
                WarningMsgFmt("The BASINS download directory ({0}) was not found; you must first download data using BASINS, then you can import them to WRDB.", path.Replace("\", "\\"))
                Return ""
            End If
            Dim files As System.Collections.ObjectModel.ReadOnlyCollection(Of String) = My.Computer.FileSystem.GetFiles(path, FileIO.SearchOption.SearchTopLevelOnly, wildcard)
            Dim tbl As String = ""
            If files.Count = 0 Then
                WarningMsgFmt("The no files were found in the BASINS download directory ({0}); you must first download data using BASINS, then you can import them to WRDB.", path.Replace("\", "\\"))
                Return ""
            ElseIf files.Count = 1 Then
                Return IO.Path.GetFileNameWithoutExtension(files(0))
            Else 'must select which one you want
                With New frmSelect(False)
                    For Each f As String In files
                        .lstItems.Items.Add(IO.Path.GetFileNameWithoutExtension(f))
                    Next
                    .Text = "Select the desired layer to import"
                    If .ShowDialog(Me) = Windows.Forms.DialogResult.Cancel Then Return Nothing Else Return .lstItems.Text
                End With
            End If
        Catch ex As Exception
            ErrorMsg(, ex)
            Return Nothing
        End Try

    End Function

    Private Function ImportMet(ByVal Scenario As enumMet) As Boolean
        Try
            Dim tbl As String = GetFile(_GISProjectPath & "\met", "met*.wdm")
            Dim dbffile As String = _GISProjectPath & "\met\" & tbl & ".dbf"
            If Not My.Computer.FileSystem.FileExists(dbffile) Then
                WarningMsg("Unable to find " & dbffile)
                Return False
            End If
            If tbl = Nothing Then Return False Else If tbl = "" Then Return True

            Dim dt As DataTable = Nothing

            'keep track of stations so can import to support table if necessary
            Dim lstStations As New Generic.List(Of String)
            Dim dr As DbDataReader = Project.DB.ExecuteReader("SELECT STATION_ID FROM STATIONS")
            While dr IsNot Nothing AndAlso dr.Read
                lstStations.Add(dr.GetString(0))
            End While
            dr.Close()

            'import station info from dbf file associated with shp file
            Dim DB As New clsDBDBase
            With DB
                .DatabaseType = clsDB.enumDBType.DBase
                .DataSource = _GISProjectPath & "\met"
                .CreateConnection()
                If Not .AddTable(dt, "SELECT * FROM " & tbl) Then Return False
                Dim sw As New IO.StreamWriter(clsProject.TempPath & "\Stations.txt", False)
                sw.WriteLine(StringFormat("Station_ID\tStation_Name\tStation_Type\tLatitude\tLongitude"))
                For Each row As DataRow In dt.Rows
                    With row
                        Dim StaID As String = Strings.Left(.Item("LOCATION"), 25).ToUpper
                        If Not lstStations.Contains(StaID) Then
                            lstStations.Add(StaID)
                            sw.WriteLine(StringFormat("{0}\t{1}\tMET\t{2}\t{3}", StaID, Strings.Left(Proper(.Item("STANAM")), 60), .Item("LATITUDE"), .Item("LONGITUDE")))
                        End If
                    End With
                Next
                sw.Close()
                sw.Dispose()
                dt.Dispose()
                .Connection.Close()
                .Dispose()
            End With
            DB = Nothing

            Project.ImportTable("Stations", clsProject.TempPath & "\Stations.txt", True)

            'keep track of pcodes so can import to support table if necessary
            Dim lstPCodes As New Generic.List(Of String)
            dr = Project.DB.ExecuteReader("SELECT PCODE FROM PCODES")
            While dr IsNot Nothing AndAlso dr.Read
                lstPCodes.Add(dr.GetString(0))
            End While
            dr.Close()

            With _WRDBImport
                .PCodeConvGroup = cboConvGroup.Text
                .ImportFilename = _GISProjectPath & "\met\" & tbl & ".wdm"
                .AutoContinue = True
                .AutoContinueDelay = 0
                .SkipPreview = True

                .SetValidList(Import.clsWRDBImport.enumTables.tStationTable, lstStations)
                .SetValidList(Import.clsWRDBImport.enumTables.tPCodeTable, lstPCodes)

                .ValidateSupport = True
                .WDMScenario = Choose(Scenario + 1, "Observed", "Computed")
                If .ShowPreview(Me) Then
                    If Project.ImportTable(ActiveBrowser.TableName, .DataTable, True) Then
                        clsApplicationSettings.ResetEditTime()
                    End If
                    If .ValidateSupport Then 'also import any records that may have been added to the support tables
                        For tt As clsProject.enumTableTypes = clsProject.enumTableTypes.Stations To clsProject.enumTableTypes.PCodeGrp
                            If Not Project.ImportTable(Project.TableName(tt), .PrivateDir & Project.TableName(tt) & ".txt", True) Then Exit For
                        Next
                    End If
                Else
                    Return False
                End If

                Return True
            End With

            Return True
        Catch ex As DbSqlException
            WarningMsg(ex.Message)
            Return False
        Catch ex As Exception
            ErrorMsg(, ex)
            Return False
        End Try
    End Function

    Private Function ImportUsgs(ByVal UsgsType As enumUsgs) As Boolean
        Try
            'import station info from dbf file associated with shp file
            Dim tbl As String = GetFile(_GISProjectPath & "\nwis", String.Format("NWIS_Stations_{0}*.dbf", Choose(UsgsType + 1, "measurements", "discharge", "qw")))
            If tbl = Nothing Then Return False Else If tbl = "" Then Return True

            Dim dbffile As String = _GISProjectPath & "\nwis\" & tbl & ".dbf"
            If Not My.Computer.FileSystem.FileExists(dbffile) Then
                WarningMsg("Unable to find " & dbffile)
                Return False
            End If

            Dim dt As DataTable = Nothing
            Dim ValidStations As New Generic.List(Of String)
            Dim DB As New clsDBDBase
            With DB
                .DatabaseType = clsDB.enumDBType.DBase
                .DataSource = _GISProjectPath & "\nwis"
                .CreateConnection()
                If Not .AddTable(dt, "SELECT * FROM " & tbl) Then Return False
                Dim sw As New IO.StreamWriter(clsProject.TempPath & "\Stations.txt", False)
                sw.WriteLine("Station_ID\tStation_Name\tStation_Type\tAgency\tLatitude\tLongitude\tHUC\tDr_Area\tElevation".Replace("\t", vbTab))
                For Each row As DataRow In dt.Rows
                    With row
                        sw.Write(Strings.Left(.Item("SITE_NO"), 25) & vbTab)
                        sw.Write(Strings.Left(Proper(.Item("STATION_NM")), 60) & vbTab)
                        sw.Write("NWIS " & Choose(UsgsType + 1, "Measurements", "Discharge", "WQ") & vbTab)
                        sw.Write(Strings.Left(.Item("AGENCY_CD"), 10) & vbTab)
                        sw.Write(Val(.Item("DEC_LAT_VA")) & vbTab)
                        sw.Write(Val(.Item("DEC_LONG_V")) & vbTab)
                        sw.Write(Strings.Left(TestNull(.Item("HUC_CD"), ""), 14) & vbTab)
                        sw.Write(.Item("DRAIN_AREA") & vbTab)
                        sw.Write(.Item("ALT_VA") & vbCrLf)
                        ValidStations.Add(Strings.Left(.Item("SITE_NO"), 25))
                    End With
                Next
                sw.Close()
                sw.Dispose()
                dt.Dispose()
                .Connection.Close()
                .Dispose()
            End With
            DB = Nothing

            Project.ImportTable("Stations", clsProject.TempPath & "\Stations.txt", True)
            My.Computer.FileSystem.DeleteFile(clsProject.TempPath & "\Stations.txt")

            With _WRDBImport
                Dim Path As String = _GISProjectPath & "\NWIS"
                If Not My.Computer.FileSystem.DirectoryExists(Path) Then Return True
                Dim files As System.Collections.ObjectModel.ReadOnlyCollection(Of String) = My.Computer.FileSystem.GetFiles(Path, FileIO.SearchOption.SearchTopLevelOnly, String.Format("NWIS_{0}*.rdb", Choose(UsgsType + 1, "measurements", "discharge", "wq")))
                If files.Count = 0 Then Return True
                Dim s As String = ""
                For i As Integer = 0 To files.Count - 1
                    s &= IIf(s = "", "", ";") & files(i)
                Next
                .ImportFilename = s
                .AutoContinue = True
                .AutoContinueDelay = 0
                .SkipPreview = True
                .SetValidList(Import.clsWRDBImport.enumTables.tStationTable, ValidStations)
                .ValidateSupport = True
                If .ShowPreview(Me) Then
                    If Project.ImportTable(ActiveBrowser.TableName, .DataTable, True) Then
                        clsApplicationSettings.ResetEditTime()
                    End If
                    If .ValidateSupport Then 'also import any records that may have been added to the support tables
                        For tt As clsProject.enumTableTypes = clsProject.enumTableTypes.Stations To clsProject.enumTableTypes.PCodeGrp
                            If Not Project.ImportTable(Project.TableName(tt), .PrivateDir & Project.TableName(tt) & ".txt", True) Then Exit For
                        Next
                    End If
                Else
                    Return False
                End If
                Return True
            End With
        Catch ex As Exception
            ErrorMsg(, ex)
            Return False
        End Try
    End Function

    Private Function ImportStoret() As Boolean
        Try
            'import station info from sta files; just replace first line with valid column headings and directly import
            '(note: import routine will ignore any unrecognized columns)

            'keep track of stations so can import to support table if necessary
            Dim lstStations As New Generic.List(Of String)
            Dim dr As DbDataReader = Project.DB.ExecuteReader("SELECT STATION_ID FROM STATIONS")
            While dr IsNot Nothing AndAlso dr.Read
                lstStations.Add(dr.GetString(0))
            End While
            dr.Close()


            Dim sw As New IO.StreamWriter(clsProject.TempPath & "\Stations.txt", False)
            sw.WriteLine("Station_ID\tStation_Name\tAgency\tLatitude\tLongitude\tHUC\tRiver_Mile\tReach_ID\tOther\tStation_Type\tRemarks".Replace("\t", vbTab))

            For Each stafile As String In My.Computer.FileSystem.GetFiles(_GISProjectPath & "\STORET-Legacy", FileIO.SearchOption.SearchTopLevelOnly, "*.sta")
                Dim sr As New IO.StreamReader(stafile)
                sr.ReadLine() 'skip header line
                Dim lof As Long = sr.BaseStream.Length
                Do While sr.Peek > 0
                    Dim ar() As String = sr.ReadLine.Split(vbTab)
                    If ar.Length = 17 Then
                        Dim Agency As String = Strings.Left(ar(0), 10)
                        Dim StaID As String = Strings.Left(ar(1), 25)
                        Dim StaNm As String = Strings.Left(Proper(ar(2)), 60)
                        Dim Lat As Single = Val(ar(4))
                        Dim Lng As Single = Val(ar(5))
                        Dim HUC As String = ar(6)
                        Dim RM As Single = Val(ar(8))
                        Dim RchID As String = Strings.Left(ar(10), 25)
                        Dim Other As String = Strings.Left(ar(11), 60)
                        Dim StaTyp As String = Strings.Left(Proper(ar(12)), 60)
                        Dim Remarks As String = Strings.Left(Proper(ar(16)), 50)
                        If Not lstStations.Contains(StaID) Then
                            lstStations.Add(StaID)
                            sw.WriteLine(StringFormat("{0}\t{1}\t{2}\t{3}\t{4}\t{5}\t{6}\t{7}\t{8}\t{9}\t{10}", StaID, StaNm, Agency, Lat, Lng, HUC, RM, RchID, Other, StaTyp, Remarks))
                        End If
                    End If
                    If Not MainForm.WriteProgress(sr.BaseStream.Position, lof, "Converting " & stafile, ProgressBarStyle.Blocks, True) Then Return False
                Loop
                sr.Close()
                sr.Dispose()
            Next

            sw.Close()
            sw.Dispose()

            Project.ImportTable("Stations", clsProject.TempPath & "\Stations.txt", True)

            'keep track of pcodes so can import to support table if necessary
            Dim lstPCodes As New Generic.List(Of String)
            dr = Project.DB.ExecuteReader("SELECT PCODE FROM PCODES")
            While dr IsNot Nothing AndAlso dr.Read
                lstPCodes.Add(dr.GetString(0))
            End While
            dr.Close()

            'import data from res files; can't just replace first line because need to combine dates and times
            'to improve speed, don't use import routines that have a lot of overhead

            sw = New IO.StreamWriter(clsProject.TempPath & "\StoretData.txt", False)
            sw.WriteLine("Station_ID\tPCode\tDate_Time\tRCode\tResult".Replace("\t", vbTab))

            For Each resfile As String In My.Computer.FileSystem.GetFiles(_GISProjectPath & "\STORET-Legacy", FileIO.SearchOption.SearchTopLevelOnly, "*.res")
                Dim sr As New IO.StreamReader(resfile)
                sr.ReadLine() 'skip header line
                Dim lof As Long = sr.BaseStream.Length
                Do While sr.Peek > 0
                    Dim ar() As String = sr.ReadLine.Split(vbTab)
                    If ar.Length = 18 Then
                        If ar(7) = "2500" Then
                            ar(7) = "00:00"
                        ElseIf ar(7).Length = 4 Then
                            ar(7) = ar(7).Insert(2, ":")
                        Else
                            ar(7) = "00:00"
                        End If
                        If Not IsDate(ar(7)) Then ar(7) = "00:00"
                        Dim dt As Date = MyCDate(ar(6) & " " & ar(7))
                        Dim rcode As String = ar(3)
                        Select Case rcode
                            Case "K" : rcode = "<"
                            Case "@" : rcode = ""
                            Case "L" : rcode = ">"
                            Case "P" : rcode = "T"
                            Case "T" : rcode = "N"
                            Case "M" : rcode = "<"
                            Case "<" : rcode = "<"
                            Case ">" : rcode = ">"
                            Case Else
                                rcode = ""
                        End Select
                        sw.WriteLine(String.Format("{0}\t{1}\t{2}\t{3}\t{4}", ar(1), ar(5), dt.ToString(MyDateTimeFormat), rcode, ar(2)).Replace("\t", vbTab))
                        'If Not lstPCodes.Contains(ar(5)) AndAlso Not PCodes.Contains(ar(5)) Then PCodes.Add(ar(5))
                    End If
                    If Not MainForm.WriteProgress(sr.BaseStream.Position, lof, "Converting " & resfile, ProgressBarStyle.Blocks, True) Then Return False
                Loop
                sr.Close()
                sr.Dispose()
            Next

            sw.Close()
            sw.Dispose()

            With _WRDBImport
                .UseHeadings = True
                .Delimiters = vbTab
                .ImportFilename = clsProject.TempPath & "\StoretData.txt"
                .AutoContinue = True
                .AutoContinueDelay = 0
                .SkipPreview = True

                .SetValidList(Import.clsWRDBImport.enumTables.tStationTable, lstStations)
                .SetValidList(Import.clsWRDBImport.enumTables.tPCodeTable, lstPCodes)

                .ValidateSupport = True
                If .ShowPreview(Me) Then
                    If Project.ImportTable(ActiveBrowser.TableName, .DataTable, True) Then
                        clsApplicationSettings.ResetEditTime()
                    End If
                    If .ValidateSupport Then 'also import any records that may have been added to the support tables
                        For tt As clsProject.enumTableTypes = clsProject.enumTableTypes.Stations To clsProject.enumTableTypes.PCodeGrp
                            If Not Project.ImportTable(Project.TableName(tt), .PrivateDir & Project.TableName(tt) & ".txt", True) Then Exit For
                        Next
                    End If
                Else
                    Return False
                End If
            End With

            Return True

        Catch ex As Exception
            ErrorMsg(, ex)
            Return False
        End Try
    End Function

    Private Function ImportStoretModern() As Boolean
        Try
            Dim tbl As String = GetFile(_GISProjectPath & "\STORET", "storet.dbf")
            Dim dbffile As String = _GISProjectPath & "\STORET\storet.dbf"
            If Not My.Computer.FileSystem.FileExists(dbffile) Then
                WarningMsg("Unable to find " & dbffile)
                Return False
            End If
            If tbl = Nothing Then Return False Else If tbl = "" Then Return True

            Dim ValidStations As New Generic.List(Of String)
            Dim dt As DataTable = Nothing

            'import station info from dbf file associated with shp file
            Dim DB As New clsDBDBase
            With DB
                .DatabaseType = clsDB.enumDBType.DBase
                .DataSource = _GISProjectPath & "\storet"
                .CreateConnection()
                If Not .AddTable(dt, "SELECT * FROM " & tbl) Then Return False
                Dim sw As New IO.StreamWriter(clsProject.TempPath & "\StoretStations.txt", False)
                sw.WriteLine("Station_ID\tStation_Name\tStation_Type\tLatitude\tLongitude\tAgency".Replace("\t", vbTab))
                For Each row As DataRow In dt.Rows
                    With row
                        sw.Write(Strings.Left(.Item("LOCID"), 25).Trim & vbTab)
                        sw.Write(Strings.Left(Proper(.Item("LOCNAME")), 60).Trim.Replace("`", "") & vbTab)
                        sw.Write(Strings.Left(Proper(.Item("LOCTYPE")), 60).Trim & vbTab)
                        sw.Write(Math.Round(Val(.Item("LATITUDE")), 4) & vbTab)
                        sw.Write(Math.Round(Val(.Item("LONGITUDE")), 4) & vbTab)
                        sw.Write(Strings.Left(.Item("ORGID"), 10).Trim & vbCrLf)
                        ValidStations.Add(Strings.Left(.Item("LOCID"), 25).Trim)
                    End With
                Next
                sw.Close()
                sw.Dispose()
                dt.Dispose()
                .Connection.Close()
                .Dispose()
            End With
            DB = Nothing

            Project.ImportTable("Stations", clsProject.TempPath & "\StoretStations.txt", True)
            'My.Computer.FileSystem.DeleteFile(TempPath & "\Stations.txt")

            For Each resfile As String In My.Computer.FileSystem.GetFiles(_GISProjectPath & "\STORET", FileIO.SearchOption.SearchTopLevelOnly, "*.STORETresults")
                With _WRDBImport
                    .PCodeConvGroup = cboConvGroup.Text
                    .ImportFilename = resfile
                    .AutoContinue = True
                    .AutoContinueDelay = 0
                    .SkipPreview = True
                    .SetValidList(Import.clsWRDBImport.enumTables.tStationTable, ValidStations)
                    .ValidateSupport = True
                    If .ShowPreview(Me) Then
                        If Project.ImportTable(ActiveBrowser.TableName, .DataTable, True) Then
                            clsApplicationSettings.ResetEditTime()
                        End If
                        If .ValidateSupport Then 'also import any records that may have been added to the support tables
                            For tt As clsProject.enumTableTypes = clsProject.enumTableTypes.Stations To clsProject.enumTableTypes.PCodeGrp
                                If Not Project.ImportTable(Project.TableName(tt), .PrivateDir & Project.TableName(tt) & ".txt", True) Then Exit For
                            Next
                        End If
                    Else
                        Return False
                    End If
                End With
            Next

            Return True
        Catch ex As DbSqlException
            WarningMsg(ex.Message)
            Return False
        Catch ex As Exception
            ErrorMsg(, ex)
            Return False
        End Try
    End Function

    ''' <summary>
    ''' No longer used!
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function ImportWQObs() As Boolean
        Try
            Dim tbl As String = GetFile(_GISProjectPath, "wqobs*.dbf")
            If tbl = Nothing Then Return False Else If tbl = "" Then Return True

            Dim dt As DataTable = Nothing
            'import station info from dbf file associated with shp file

            Dim DB As New clsDBDBase
            With DB
                .DatabaseType = clsDB.enumDBType.DBase
                .DataSource = _GISProjectPath
                .CreateConnection()
                If Not .AddTable(dt, "SELECT * FROM " & tbl) Then Return False

                Dim sw As New IO.StreamWriter(clsProject.TempPath & "\Stations.txt", False)
                sw.WriteLine("Station_ID\tStation_Name\tStation_Type\tAgency\tLatitude\tLongitude\tRiver_Mile\tHUC".Replace("\t", vbTab))
                For Each row As DataRow In dt.Rows
                    With row
                        sw.Write(.Item("BSTAT_ID") & vbTab)
                        sw.Write(Proper(.Item("LOCATION")) & vbTab)
                        sw.Write(.Item("TYPE") & vbTab)
                        sw.Write(.Item("AGENCY") & vbTab)
                        sw.Write(.Item("LAT") & vbTab)
                        sw.Write(.Item("LONG") & vbTab)
                        sw.Write(.Item("MILE") & vbTab)
                        sw.Write(.Item("BCU") & vbCrLf)
                    End With
                Next
                sw.Close()
                sw.Dispose()
                dt.Dispose()
                .Connection.Close()

                Project.ImportTable("Stations", clsProject.TempPath & "\Stations.txt", True)

                'create list of pcodes that will import
                Dim lstPCode As New Generic.List(Of String)

                'import data from dbf file in data directory
                .DataSource &= "\wqobs"
                .CreateConnection()
                For Each s As String In .GetTableList()
                    If Not .AddTable(dt, "SELECT * FROM " & s) Then Return False

                    sw = New IO.StreamWriter(clsProject.TempPath & "\Data.txt", False)
                    sw.WriteLine("Station_ID\tPCode\tDate_Time\tRCode\tResult".Replace("\t", vbTab))
                    For Each row As DataRow In dt.Rows
                        With row
                            sw.Write(.Item("BSTAT_ID") & vbTab)

                            Dim pcode As String = TestNull(.Item("PARM"), "")

                            _WRDBImport.ConvertGroup.ConvertValue(cboConvGroup.Text, pcode)
                            If Not lstPCode.Contains(pcode) Then lstPCode.Add(pcode)

                            sw.Write(pcode & vbTab)
                            If Not lstPCode.Contains(pcode) Then lstPCode.Add(pcode)
                            Dim datestr As String = .Item("DATE")
                            Dim timestr As String = TestNull(.Item("TIME"), "0000")
                            sw.Write(MyCDate(String.Format("{0}/{1}/{2} {3}:{4}", datestr.Substring(4, 2), datestr.Substring(6, 2), datestr.Substring(0, 4), timestr.Substring(0, 2), timestr.Substring(2, 2))).ToString(MyDateTimeFormat) & vbTab)
                            Dim remark As String = TestNull(.Item("REMARK"), "")
                            Dim rcode As String
                            Select Case remark
                                Case "K" : rcode = "<"
                                Case "@" : rcode = ""
                                Case "L" : rcode = ">"
                                Case "P" : rcode = "T"
                                Case "T" : rcode = "N"
                                Case "M" : rcode = "<"
                                Case "<" : rcode = "<"
                                Case ">" : rcode = ">"
                                Case Else
                                    rcode = ""
                            End Select
                            sw.Write(rcode & vbTab)
                            sw.Write(.Item("VALUE") & vbCrLf)
                        End With
                    Next
                    sw.Close()
                    sw.Dispose()
                    dt.Dispose()
                    .Connection.Close()
                    Project.ImportTable(ActiveBrowser.TableName, clsProject.TempPath & "\Data.txt", True)
                Next

                sw = New IO.StreamWriter(clsProject.TempPath & "\PCodes.txt", False)
                sw.WriteLine("PCode\tAnal_Name".Replace("\t", vbTab))
                For Each pcode As String In lstPCode
                    sw.WriteLine(pcode & vbTab & "Unknown")
                Next
                sw.Close()
                sw.Dispose()
                Project.ImportTable("PCodes", clsProject.TempPath & "\PCodes.txt", True)

                Return True
            End With
        Catch ex As Exception
            ErrorMsg(, ex)
            Return False
        End Try
    End Function

    ''' <summary>
    ''' No longer used!
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function ImportPCS() As Boolean
        Try
            Dim tbl As String = GetFile(_GISProjectPath, "pcs*.dbf")
            If tbl = Nothing Then Return False Else If tbl = "" Then Return True

            'import station info from dbf file associated with shp file
            Dim csb As New OleDb.OleDbConnectionStringBuilder
            Dim cn As New OleDb.OleDbConnection()
            Dim dt As New DataTable
            With csb
                .Provider = "Microsoft.Jet.OLEDB.4.0"
                .Item("Extended Properties") = "DBASE III"
                .DataSource = _GISProjectPath
                cn.ConnectionString = .ConnectionString
            End With
            Try
                cn.Open()
            Catch ex As Exception
                ErrorMsg("Unable to open table " & tbl & " for processing; it may be corrupted.", ex)
                Return True
            End Try
            Dim da As New OleDb.OleDbDataAdapter("SELECT * FROM " & tbl, cn)
            da.SelectCommand.CommandTimeout = 60
            da.Fill(dt)
            Dim sw As New IO.StreamWriter(clsProject.TempPath & "\Stations.txt", False)
            sw.WriteLine("Station_ID\tStation_Name\tStation_Type\tAgency\tLatitude\tLongitude\tRiver_Mile\tHUC\tReach_ID".Replace("\t", vbTab))
            For Each row As DataRow In dt.Rows
                With row
                    sw.Write(Strings.Left(.Item("NPDES"), 25) & vbTab)
                    sw.Write(Strings.Left(Proper(.Item("FAC_NAME")), 60) & vbTab)
                    sw.Write("PCS" & vbTab)
                    sw.Write(Strings.Left(.Item("OWNERSHIP"), 10) & vbTab)
                    sw.Write(Val(.Item("BLAT")) & vbTab)
                    sw.Write(Val(.Item("BLONG")) & vbTab)
                    sw.Write(.Item("STREAM_MIL") & vbTab)
                    sw.Write(Strings.Left(.Item("BCU"), 14) & vbTab)
                    sw.Write(Strings.Left(TestNull(.Item("REC_WATER"), ""), 25) & vbCrLf)
                End With
            Next
            sw.Close()
            sw.Dispose()
            cn.Close()
            Project.ImportTable("Stations", clsProject.TempPath & "\Stations.txt", True)

            'create list of pcodes that will import
            Dim lstPCode As New Generic.List(Of String)

            'import data from dbf file in data directory
            csb.DataSource &= "\pcs"
            cn.ConnectionString = csb.ConnectionString
            cn.Open()
            sw = New IO.StreamWriter(clsProject.TempPath & "\Data.txt", False)
            sw.WriteLine("Station_ID\tPCode\tDate_Time\tRCode\tResult".Replace("\t", vbTab))
            For Each f As String In My.Computer.FileSystem.GetFiles(_GISProjectPath & "\pcs", FileIO.SearchOption.SearchTopLevelOnly, "*.csv")
                Dim sr As New IO.StreamReader(f)
                sr.ReadLine()
                While Not sr.EndOfStream
                    Dim LastLine As String = sr.ReadLine
                    Dim ar() As String = LastLine.Split(",")
                    'write the average value and the period end date; pcode is padded with 0
                    If ar.Length >= 9 AndAlso IsDate(ar(9)) AndAlso IsNumeric(ar(2)) Then
                        Dim rcode As String = ""
                        If ar(2).StartsWith("<") Or ar(2).StartsWith(">") Then
                            rcode = ar(2).Substring(0, 1)
                            ar(2) = ar(2).Substring(1)
                        End If
                        Dim pcode As String = String.Format("{0:00000}", Val(ar(11)))
                        _WRDBImport.ConvertGroup.ConvertValue(cboConvGroup.Text, pcode)
                        If Not lstPCode.Contains(pcode) Then lstPCode.Add(pcode)
                        If Val(ar(2)) <> 0 Then sw.WriteLine(String.Format("{0}\t{1}\t{2}\t{3}\t{4}", ar(0), pcode, ar(9), rcode, Val(ar(2))).Replace("\t", vbTab))
                    End If
                End While
            Next
            sw.Close()
            sw.Dispose()
            cn.Close()
            Project.ImportTable(ActiveBrowser.TableName, clsProject.TempPath & "\Data.txt", True)

            sw = New IO.StreamWriter(clsProject.TempPath & "\PCodes.txt", False)
            sw.WriteLine("PCode\tAnal_Name".Replace("\t", vbTab))
            For Each pcode As String In lstPCode
                sw.WriteLine(pcode & vbTab & "Unknown")
            Next
            sw.Close()
            sw.Dispose()
            Project.ImportTable("PCodes", clsProject.TempPath & "\PCodes.txt", True)

            cn.Close()
            cn.Dispose()
            dt.Dispose()
            da.Dispose()
            Return True
        Catch ex As Exception
            ErrorMsg(, ex)
            Return False
        End Try

    End Function

    <CLSCompliant(False)> _
    Public Sub New(ByVal GISProjectPath As String, ByRef WRDBImport As WRDB.Import.clsWRDBImport)

        ' This call is required by the Windows Form Designer.
        InitializeComponent()

        ' Add any initialization after the InitializeComponent() call.
        _GISProjectPath = GISProjectPath
        _WRDBImport = WRDBImport

        GetWindowPos(REGAPP, Me)
    End Sub

    Private Sub chkAll_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles chkAll.Click
        For Each cntl As Control In Panel1.Controls
            CType(cntl, CheckBox).Checked = chkAll.Checked
        Next
    End Sub

    Private Sub chkMet_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles chkMetObs.Click, chkMetComp.Click, chkSTORETModern.Click, chkSTORETLegacy.Click, chkSTORETMod.Click, chkUSGSDaily.Click, chkUSGSFlow.Click, chkUSGSWQ.Click
        Dim allChecked As Boolean = True
        Dim allUnchecked As Boolean = True
        For Each cntl As Control In Panel1.Controls
            If CType(cntl, CheckBox).Checked Then allUnchecked = False Else allChecked = False
        Next
        If allChecked Then
            chkAll.CheckState = CheckState.Checked
        ElseIf allUnchecked Then
            chkAll.CheckState = CheckState.Unchecked
        Else
            chkAll.CheckState = CheckState.Indeterminate
        End If
    End Sub

    Private Sub frmImportGIS_FormClosed(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
        SaveSetting(REGAPP, Name, "cboConvGroup", cboConvGroup.Text)
        SaveWindowPos(REGAPP, Me)
    End Sub

    Private Sub frmImportGIS_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Project.FillPickList(cboConvGroup, "", "ConvGrp", "ConvGroup", "", "(None)", GetSetting(REGAPP, Name, "cboConvGroup", "(None)"))
    End Sub

    Private Sub btnHelp_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnHelp.Click
        ShowHelp(Me, "10")
    End Sub
End Class
